package com.jxb.service;

import java.util.ArrayList;
import java.util.List;

import org.omg.CORBA.PRIVATE_MEMBER;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.jxb.mapper.PermissionMapper;
import com.jxb.mapper.UserMapper;
import com.jxb.pojo.Permission;
import com.jxb.pojo.User;

/**
 * 用户认证逻辑
 *
 * @author jiaobo
 * @date Created in 2024/10/26 13:45
 **/
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    public User getByUsername(String username) {
        return userMapper.getByUsername(username);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从mysql查询用户
        User user = getByUsername(username);
        List<GrantedAuthority> authorities = new ArrayList<>();
        if (user != null) {
            List<Permission> permissions = permissionMapper.selectByUserId(user.getId());
            permissions.forEach(permission -> {
                if (permission != null && !StringUtils.isEmpty(permission.getEnname())) {
                    SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission.getEnname());
                    authorities.add(simpleGrantedAuthority);
                }
            });
            return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
        }else {
            throw  new UsernameNotFoundException("用户名不存在");
        }

    }
}
